const express = require("express");
const route = express.Router();
const path = require('path')
//引入fromDate格式解析器
const formidable = require('formidable')
const advModel = require("../db/model/advModel")
const isLoginMiddle = require('../middleware/isLoginMiddle')

//写个接口，使用封装好的权限验证中间件
//添加广告接口
route.post("/addAdv", isLoginMiddle, async (req, res) => {

    const form = formidable({
        uploadDir: path.resolve(__dirname, "../upload"),
        keepExtensions: true
    })
    //在解析的params里面拿到传递的前台传递的数据

    form.parse(req, async (err, params, file) => {
        const {
            advTitle,
            advType,
            advOrder
        } = params
        //向数据库添加数据
        try {
            await advModel.create({
                advTitle,
                advType,
                advOrder,
                advHref: "/upload" + file.advPic.newFilename,
                addTime: new Date().toLocaleString()
            })

            return res.send({
                code:10000,
                msg : '添加广告成功',
                data:null
            })
        } catch (e) {
            return res.send({
                code:10001,
                msg : '添加广告数据库操作出现异常:' + e.message,
                data:null
            })
        }
    })

})
module.exports = route;